//
//  FirstTableViewController.m
//  华康通
//
//  Created by leiyu on 16/9/23.
//  Copyright © 2016年 com.huakang. All rights reserved.
//

#import "FirstTableViewController.h"
#import "FirstPageSectionButtonsView.h"
#import "FirstPageProductCell.h"
#import "ProductDetailViewController.h"
#import "NewsIformationController.h"
#import "AboutUSController.h"
#import "VidoCollectionController.h"
#import "JSONFromProduct.h"
#import "JSONFromGroupTypeList.h"
#import "NoMoneyListViewController.h"
#import "UMMobClick/MobClick.h"
#import "JSONFromImages.h"
#import "NewsIformationDetailController.h"
#import "MainMessagesController.h"
#import "LYMessageList.h"
#import "HDH5ViewController.h"

#define RODIO (186.0/375.0)



@interface FirstTableViewController ()<SDCycleScrollViewDelegate, UITableViewDelegate, UITableViewDataSource,UIScrollViewDelegate,LMJScrollTextView2Delegate>


//@property (nonatomic, strong) NSString* str;
@property (nonatomic, strong) NSMutableArray* products1;

@property (nonatomic, strong) NSArray* sectionLists1;

@property (nonatomic, strong) NSArray* imagesURLStrings1;

@property (nonatomic, strong) UIView* headerView;
@property (nonatomic, strong) NSArray* imageNames;
//@property (nonatomic, strong) NSArray* imagesURLStrings;
@property (nonatomic, strong) UIImageView* headerImageView;
@property (nonatomic, strong) UIView* imageBackView;
@property (nonatomic, strong) FirstPageButtonsView* buttonsView;
@property (nonatomic, strong) FirstPageSectionButtonsView* sectionButtonsView;
//记录是否为全部产品、限时优惠等按钮的下标
@property (nonatomic, unsafe_unretained) NSInteger buttonIndex;
//产品列表数量
//@property (nonatomic, strong) NSMutableArray* products;
//用一个数来记录用户上拉加载的次数
@property (nonatomic, unsafe_unretained) NSInteger slCount;
@property (nonatomic, strong) MJRefreshAutoGifFooter *footer;
@property (nonatomic, strong) MJRefreshNormalHeader *header;
//记录secion上的按钮数组
//@property (nonatomic, strong) NSArray* sectionLists;
//记录全部产品、限时优惠、热卖劲爆的type
@property (nonatomic, strong) NSString* group_type_id;
//用户工号
@property (nonatomic, strong) NSString* agentCode;

@property (nonatomic, strong) ShowNoNetworkView* workView;
//表section的滚动视图的滚动距离
@property (nonatomic, unsafe_unretained) CGFloat distance;
//表上拉加载时的滚动视图的滚动距离
@property (nonatomic, unsafe_unretained) CGFloat reloadDataDistance;

@property (nonatomic, strong) UIButton* messageButton;
//保存原来的frame
@property (nonatomic, unsafe_unretained) CGRect frame;
//
@property (nonatomic, strong) UIView* xxView;

//创建滚动消息展示
@property (nonatomic, strong) LMJScrollTextView2 * scrollTextView;

//消息的json数组
@property (nonatomic, strong) NSArray* messages;


//用于未无网络情况下，显示产品列表的数组
@property (nonatomic, strong) NSArray* noNetworkArr;

//表上下滚动的滚动距离
//@property (nonatomic, unsafe_unretained) CGFloat myDistance;

@end

@implementation FirstTableViewController



- (void)viewDidDisappear:(BOOL)animated
{
    NSLog(@"首页消失——————————————————————————————————————————————");
}

- (UIButton*)messageButton
{
    if (!_messageButton)
    {
        _messageButton = [[UIButton alloc]init];
        _messageButton.frame = CGRectMake(UISCREENWEITH - 76,  UISCREENHEIGHT - TabBarHeight - 76, 50, 50);
        [_messageButton setImage:LoadImage(@"home_notes_top_change") forState:UIControlStateNormal];
        //无消息 展示图标 home_notes_top
        //有消息 展示图标 home_notes_top_change
        [_messageButton setTitleColor:FFFFFFColor forState:UIControlStateNormal];
        _messageButton.layer.cornerRadius = 20.0;
        _messageButton.layer.masksToBounds = NO;
        _messageButton.layer.shadowOffset = CGSizeMake(1, 1);
        _messageButton.layer.shadowOpacity = 0.4;
        _messageButton.layer.shadowColor = [UIColor grayColor].CGColor;
        [_messageButton addTarget:self action:@selector(pushMessageVC) forControlEvents:UIControlEventTouchUpInside];
    }
    return _messageButton;
}

//创建一个悬浮按钮 可以点击推出消息
- (void)createMessageButton
{
    //创建一个悬浮按钮 可以点击推出消息
    // [self.view addSubview:self.messageButton];
    _messageButton.hidden = NO;
    [[UIApplication sharedApplication].keyWindow addSubview:self.messageButton];
}

- (void)pushMessageVC
{
    if ([TRUserAgenCode isLogin])
    {
        MainMessagesController* messageVC = [self.storyboard instantiateViewControllerWithIdentifier:@"MainMessagesController"];
        messageVC.hidesBottomBarWhenPushed = YES;
        //    messageVC.messages = [NSMutableArray arrayWithArray:self.messages];
        [self.navigationController pushViewController:messageVC animated:YES];
    }
    else
    {
        [self judeLoginWithMessage:@"您还没登录，请先登录!"];
    }
}

- (NSMutableArray*)products1
{
    if (!_products1)
    {
        _products1 = [NSMutableArray array];
    }
    return _products1;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = LIGHTGREYColor;
    
    //初始页
    self.slCount = 1;
    //默认全查
    self.group_type_id = @"";
    
    [self.tableView registerNib:[UINib nibWithNibName:@"FirstPageProductCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"NoNetworkCell" bundle:nil] forCellReuseIdentifier:@"NoNetworkCell"];
    self.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.header setTitle:@"签单快人一步\n松开刷新数据" forState:MJRefreshStatePulling];
    [self.header setTitle:@"签单快人一步\n疯狂加载中" forState:MJRefreshStateRefreshing];
    self.header.lastUpdatedTimeLabel.hidden = YES;
    
    self.tableView.header = self.header;
    self.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // Set footer
    self.tableView.footer = self.footer;
    [self.footer setHidden:YES];
    
    //首先展示出来 模块
    [self createHeaderViewWithArray:self.imagesURLStrings1 withBool:NO];
    
    NSString* str = [CacheData getCache:@"ISSHOWTGF_666"];
    if (str == nil)
    {
        [self GCDForPost];
    }
}

- (void)GCDForPost
{
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstance];
    [networking showErrorWithSuccess:^{
        // 创建gcd group
        dispatch_group_t serviceGroup = dispatch_group_create();
        // 将任务放入 group中
        dispatch_group_enter(serviceGroup);
        //网络加载首页广告图片
        [self postPictures];
        //请求分组
        [self postGroupTypeList];
        //请求产品
        [self postPramaWithPageSize:1 withPages:10 withType:self.group_type_id];
        //请求消息数组
        [self postMessageList];
        // 在block中将任务移出group
        dispatch_group_leave(serviceGroup);
        dispatch_group_notify(serviceGroup, dispatch_get_main_queue(), ^{
            // 任务全部完成处理
            NSLog(@"完成");
            [SVProgressHUD dismiss];
        });
    } failure:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.products1 removeAllObjects];
            self.sectionLists1 = @[];
            [self endRefresh];
            self.footer.hidden = YES;
            //首先展示出来 模块
            [self createHeaderViewWithArray:self.imagesURLStrings1 withBool:NO];
            [self.tableView reloadData];
        });
    }];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSString* str = [CacheData getCache:@"ISSHOWTGF_666"];
    if (str != nil)
    {
        [self GCDForPost];
    }
    
    UIEdgeInsets contentInset = self.tableView.contentInset;
    contentInset.top = -20;
    [self.tableView setContentInset:contentInset];
//    UIView *barBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 20)];
//    barBackground.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.9];
//    [self.view addSubview:barBackground];
    self.messageButton.hidden = NO;
    self.navigationController.navigationBar.hidden = YES;
    ShowTabbar;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self setNeedsStatusBarAppearanceUpdate];
    //滚动视图的时候改变消息按钮的显示图标
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getPushNotification:) name:@"userInfoNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showMessageButton:) name:@"showButton" object:nil];
    [MobClick beginLogPageView:@"FirstTableViewController"];//("PageOne"为页面名称，可自定义)
}

- (void)showMessageButton:(NSNotification*)notification
{
    //创建一个消息按钮
    [self createMessageButton];
}

//设置状态栏背景颜色
//- (void)setStatusBarBackgroundColor:(UIColor *)color
//{
//    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
//    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
//        statusBar.backgroundColor = color;
//    }
//}

//根据通知信息跳转到不同的页面
- (void)getPushNotification:(NSNotification*)notification
{
    NSString *type = [notification valueForKey:@"type"];
    if ([type isEqualToString:@"nomoney"] && [type rangeOfString:@"http"].location == NSNotFound)
    {
        //跳转到0元赠险
        NoMoneyListViewController* nomoneyVC = [[NoMoneyListViewController alloc]initWithNibName:@"NoMoneyListViewController" bundle:nil];
        nomoneyVC.isPush = YES;
        nomoneyVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:nomoneyVC animated:YES];
    }
    else if ([type isEqualToString:@"aboutus"] && [type rangeOfString:@"http"].location == NSNotFound)
    {
        //跳转到关于我们的列表页面
        AboutUSController* aboutUSVC = [[AboutUSController alloc]initWithNibName:@"AboutUSController" bundle:nil];
        aboutUSVC.isPush = YES;
        aboutUSVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:aboutUSVC animated:YES];
    }
    else if ([type rangeOfString:@"news"].location != NSNotFound && [type rangeOfString:@"http"].location == NSNotFound)
    {
        //跳转到新闻详情页面
        NewsIformationDetailController* newDetailVC = [[NewsIformationDetailController alloc]initWithNibName:@"NewsIformationDetailController" bundle:nil];
        newDetailVC.isPush = YES;
        if (type.length > 4)
        {
            newDetailVC.url = [NSString stringWithFormat:@"%@/static/news/detail.html?newsid=%@",NEWS_URL,[type substringFromIndex:4]];
        }
        newDetailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:newDetailVC animated:YES];
    }
    else if ([type rangeOfString:@"product"].location != NSNotFound && [type rangeOfString:@"http"].location == NSNotFound)
    {
        if ([type rangeOfString:@"_"].location != NSNotFound)
        {
            //跳转到产品详情页面
            ProductDetailViewController* productDetailVC = [[ProductDetailViewController alloc]initWithNibName:@"ProductDetailViewController" bundle:nil];
            NSArray* arr = [type componentsSeparatedByString:@"_"];
            productDetailVC.productId = [arr[0] substringFromIndex:7];
            productDetailVC.isSell = arr[1];
            productDetailVC.isFirst = NO;
            productDetailVC.isPush = YES;
            productDetailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:productDetailVC animated:YES];
        }
    }
    else if ([type rangeOfString:@"http"].location != NSNotFound)
    {
        //跳转到带链接的产品活动页面
        NewsIformationDetailController* newDetailVC = [[NewsIformationDetailController alloc]initWithNibName:@"NewsIformationDetailController" bundle:nil];
        newDetailVC.isPush = YES;
        newDetailVC.url = [NSString stringWithFormat:@"%@/static/news/detail.html?newsid=%@",NEWS_URL,type];
        newDetailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:newDetailVC animated:YES];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
//    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
//    dispatch_after(delay, dispatch_get_main_queue(), ^{
//        //检查版本更新
//        CheckVersion* cv = [[CheckVersion alloc]init];
//        cv.isSetSelf = NO;
//        [cv checkBuild];
//    });
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    self.navigationController.navigationBar.hidden = NO;
    HiddenTabbar;
    self.navigationController.navigationBar.alpha = 1.0;
//    [self setStatusBarBackgroundColor:ClEARColor];
    self.messageButton.hidden = YES;

//    self.messageButton = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"userInfoNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"showButton" object:nil];
    [MobClick endLogPageView:@"FirstTableViewController"];
}


//弹出提示功能正在开发
- (void)showNoPush
{
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    TextStatusView *customView  = [TextStatusView view];
    customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
    customView.bottomLabel.text = @"该功能正在开发中，敬请期待！";
    //    customView.layer.cornerRadius = 7.0;
    //    customView.layer.masksToBounds = YES;
    [alertView setContainerView:customView];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确定", nil]];
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex)
        {
            case 0:
                return ;
                break;
            default:
                return;
                break;
        }
    }];
    [alertView show];
}

- (void)createWorkView
{
    if (self.workView == nil)
    {
        self.workView = [[ShowNoNetworkView alloc]initWithFrame:CGRectMake(0, 66 + self.headerView.frame.size.height, UISCREENWEITH, UISCREENHEIGHT - 66 - self.headerView.frame.size.height  - TabBarHeight)];
        self.workView.labelText = @"产品待开发中...";
        self.workView.imageName = @"no_record";
        self.workView.myType = MyTypeOfViewForShowError;
        [self.workView createAllSubView];
        [self.tableView addSubview:self.workView];
    }
}

- (void)removeWorkView
{
    self.workView.frame = CGRectZero;
    [self.workView removeFromSuperview];
    self.workView = nil;
}

//下拉刷新
- (void)loadNewData
{
    NSLog(@"下拉刷新");
    self.slCount = 1;
    [self.products1 removeAllObjects];
    [self.tableView.header beginRefreshing];
    [self.tableView.footer resetNoMoreData];
    [self removeWorkView];
    
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        //异步请求
        [self GCDForPost];
    });
}
//上拉加载
- (void)loadMoreData
{
    self.slCount++;
    NSLog(@"self.slCount = %ld",(long)self.slCount);
    NSLog(@"上拉加载");
    [self removeWorkView];
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        //请求数据
        [self postPramaWithPageSize:self.slCount withPages:10 withType:self.group_type_id];
    });
}
/**
 *  停止刷新
 */
-(void)endRefresh
{
    if ([self.tableView.header isRefreshing])
    {
       [self.tableView.header endRefreshing];
    }
    if ([self.tableView.footer isRefreshing])
    {
        [self.tableView.footer endRefreshing];
    }
}


//判断并且登录
- (void)judeLoginWithMessage:(NSString*)message
{
    ShowLogin(self.navigationController);
}
//网络加载首页广告图片
#pragma mark  //网络加载首页广告图片
- (void)postPictures
{
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"getPictures",
                           @"requestObject":@{
                                   @"pictureType": @"home_banner",
                                   @"platform":@"2",
                                   @"pageParams":@{
                                       @"currentPage": @"1",
                                       @"pageSize": @"20",
                                       @"queryAll": @NO
                                   }
                                }
                           };
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self getPicturesWithURL:url withParam:json withCacheStr:md5_Str];
}

//从本地或服务器读取数据
- (void)readPicturesDataWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"广告广告广告--------");
    if ([json isKindOfClass:[NSDictionary class]] && json)
    {
        if ([json[@"resultCode"] isEqualToString:@"0"])
        {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                NSMutableArray* arr = [NSMutableArray array];
                for (NSDictionary* dic in json[@"responseObject"][@"pictureList"])
                {
                    JSONFromImages* images = [JSONFromImages getPicturesWithJSON:dic];
                    [arr addObject:images];
                }
                self.imagesURLStrings1 = [arr copy];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (self.imagesURLStrings1.count > 0)
                    {
                        [self createHeaderViewWithArray:self.imagesURLStrings1 withBool:YES];
                    }
                    else
                    {
                        [self createHeaderViewWithArray:self.imagesURLStrings1 withBool:NO];
                    }
                });
                
            });
            
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self createHeaderViewWithArray:self.imagesURLStrings1 withBool:NO];
            });
        }
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self createHeaderViewWithArray:self.imagesURLStrings1 withBool:NO];
        });
    }
}

- (void)getPicturesWithURL:(NSString*)url withParam:(NSDictionary*)param withCacheStr:(NSString*)cacheStr
{
    [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
        //网络读取数据
        [self readPicturesDataWithData:responseObject];
        
    } failure:^(NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self createHeaderViewWithArray:self.imagesURLStrings1 withBool:NO];
        });
        
    }];
    
    
    
}

//创建一张本地无网络展示图
- (NSArray*)getNoNetworkImages
{
    NSMutableArray* array = [NSMutableArray array];
    [array addObject:@"home_Defaultpicture.png"];
    return [array copy];
}

//得到图片链接数组
- (NSArray*)getURLSForImagesWithArr:(NSArray*)arr
{
    NSMutableArray* array = [NSMutableArray array];
    for (JSONFromImages* images in arr)
    {
        [array addObject:images.prictureUrl];
    }
    return [array copy];
}

//创建一个消息展示标签滚动视图
- (void)createXXViewWithFloat:(CGFloat)l withIsNetwork:(BOOL)isNetwork
{
//    if (!self.xxView)
//    {
    self.xxView = [[UIView alloc]initWithFrame:CGRectMake(0, l, UISCREENWEITH, 48)];
    self.xxView.backgroundColor = FFFFFFColor;
    [self.headerView addSubview:self.xxView];
    _scrollTextView = [[LMJScrollTextView2 alloc] initWithFrame:CGRectMake(63,0, UISCREENWEITH - 126, 48)];
    _scrollTextView.delegate  = self;
    _scrollTextView.backgroundColor = FFFFFFColor;
    _scrollTextView.textColor = C3C3CColor;
    _scrollTextView.textFont = SetFont(15.0);
    NSMutableArray* arr = [NSMutableArray array];
    //只显示3条数据
    if (self.messages.count > 0)
    {
        if (self.messages.count > 3)
        {
            [arr addObject:self.messages[0]];
            [arr addObject:self.messages[1]];
            [arr addObject:self.messages[2]];
            NSLog(@"arr = %@",arr);
            _scrollTextView.textDataArr = [self getTitlesWithArr:[arr copy]];
        }
        else
        {
            _scrollTextView.textDataArr = [self getTitlesWithArr:self.messages];
        }
    }
    [self.xxView addSubview:_scrollTextView];
    [_scrollTextView startScrollBottomToTop];
    UIImageView* imageView = [[UIImageView alloc]init];
    if (isNetwork)
    {
        imageView.image = LoadImage(@"home_notes-1");
    }
    else
    {
        imageView.image = LoadImage(@"headline");
    }
    imageView.frame = CGRectMake(16, 14, 35, 20);
    [self.xxView addSubview:imageView];
}

- (void)scrollTextView2:(LMJScrollTextView2 *)scrollTextView currentTextIndex:(NSInteger)index
{
    if ([TRUserAgenCode isLogin])
    {
        if (self.messages.count > 0)
        {
            LYMessageList* list = self.messages[index];
            //推出活动页面详情
            HDH5ViewController* vc = [[HDH5ViewController alloc]initWithNibName:@"HDH5ViewController" bundle:nil];
            vc.html = [NSString stringWithFormat:@"%@?id=%@&customerId=%@",MessageURL1,list.myId,[TRUserAgenCode getCustomerId]];
            vc.small_picture = @"fre_get1.png";
            vc.product_features = list.content;
            vc.myTitle = list.title;
            vc.small_picture = list.pic;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
        else
        {
//            [self judeLoginWithMessage:@"服务端发生错误，无法获取相关数据!"];
            
        }
    }
    else
    {
        [self judeLoginWithMessage:@"您还没登录，请先登录!"];
    }
}

//创建一个滚动视图和一排按钮
- (void)createHeaderViewWithArray:(NSArray*)arr withBool:(BOOL)isTrue
{
    if (isTrue)
    {
        self.noNetworkArr = @[];
    }
    else
    {
        self.noNetworkArr = @[@"",@"",@"",@"",@"",@"",@"",@"",@"",@""];
    }
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, (UISCREENWEITH * RODIO) + 120 + 10 + 48)];
    SDCycleScrollView *cycleScrollView = nil;
    if (isTrue)
    {
        cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, UISCREENWEITH, UISCREENWEITH * RODIO) delegate:self placeholderImage:LoadImage(@"home_Defaultpicture.png")];
        cycleScrollView.imageURLStringsGroup = [self getURLSForImagesWithArr:arr];
        NSLog(@"imageURLStringsGroup = %@",cycleScrollView.imageURLStringsGroup);
        //自定义轮播时间
        cycleScrollView.autoScrollTimeInterval = 5;
    }
    else
    {
        // 本地加载图片的轮播器
        cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, UISCREENWEITH, UISCREENWEITH * RODIO) imageNamesGroup:[self getNoNetworkImages]];
        cycleScrollView.delegate = nil;
    }
    cycleScrollView.backgroundColor = FCFCFCColor;
    //当前实体圆颜色
    cycleScrollView.currentPageDotColor = FFFFFFColor;
    //小圆圈颜色
    cycleScrollView.pageDotColor = C0C0C0Color;
    //滚动视图的滚动方向
    cycleScrollView.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //页码控件的位置
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    //更改pageControl小圆圈的尺寸
    [cycleScrollView setPageControlDotSize:CGSizeMake(6, 6)];

    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    [self.headerView addSubview:cycleScrollView];
    self.buttonsView = [[FirstPageButtonsView alloc]initWithFrame:CGRectMake(0, UISCREENWEITH * RODIO, UISCREENWEITH, 120) withIsNetwork:isTrue];
    [self.buttonsView returnButtonTag:^(NSInteger buttonTag) {
        //当点击按钮，执行方法（0元赠险、华康课堂、新闻资讯、关于华康）
        NSLog(@"buttonTag = %ld",(long)buttonTag);
        switch (buttonTag)
        {
            case 0:
            {
                NoMoneyListViewController* nomoneyVC = [[NoMoneyListViewController alloc]initWithNibName:@"NoMoneyListViewController" bundle:nil];
                [nomoneyVC setHidesBottomBarWhenPushed:YES];
                                    nomoneyVC.isPush = NO;
                nomoneyVC.isPush = YES;
                nomoneyVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:nomoneyVC animated:YES];
            }
                break;
            case 1:
            {
                //华康课堂
                UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                VidoCollectionController* vidoCollectionVC = [storyboard instantiateViewControllerWithIdentifier:@"VidoCollectionVC"];
                vidoCollectionVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vidoCollectionVC animated:YES];
                
            }
                break;
            case 2:
            {
                //新闻资讯
                NewsIformationController* newsVC = [[NewsIformationController alloc]initWithNibName:@"NewsIformationController" bundle:nil];
                newsVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:newsVC animated:YES];
            }
                break;
            case 3:
            {
                //关于华康
                AboutUSController* aboutUSVC = [[AboutUSController alloc]initWithNibName:@"AboutUSController" bundle:nil];
                aboutUSVC.isPush = YES;
                aboutUSVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:aboutUSVC animated:YES];
            }
                break;
            default:
                break;
        }
    }];
    [self.headerView addSubview:self.buttonsView];
    [self createXXViewWithFloat:(UISCREENWEITH * RODIO) + 120 withIsNetwork:isTrue];
    UIView* grayView = [[UIView alloc]initWithFrame:CGRectMake(0, UISCREENWEITH * RODIO + 120 + 48, UISCREENWEITH, 10)];
    if (isTrue)
    {
        grayView.backgroundColor = LIGHTGREYColor;
    }
    else
    {
        grayView.backgroundColor = FFFFFFColor;
    }
    [self.headerView addSubview:grayView];
    self.tableView.tableHeaderView = self.headerView;
}

//立即投保
- (void)pushTBVC:(UIButton*)sender
{
    FirstPageProductCell *cell = (FirstPageProductCell *)[[sender superview]superview];
    NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
    JSONFromProduct* product = self.products1[indexPath.row];
    ProductDetailViewController* productDetailVC = [[ProductDetailViewController alloc]initWithNibName:@"ProductDetailViewController" bundle:nil];
    productDetailVC.isFirst = YES;
    productDetailVC.isPush = YES;
    productDetailVC.gotoUrl = product.gotoUrl;
    productDetailVC.productId = product.productCode;
    productDetailVC.isSell = product.isSell;
    productDetailVC.small_picture = product.small_picture;
    productDetailVC.product_features = product.product_features;
//    productDetailVC.title = product.productName;
    if (![product.gotoUrl isEqualToString:@""])
    {
        if ([TRUserAgenCode isLogin])
        {
            if ([productDetailVC.gotoUrl rangeOfString:@"{agentid}"].location != NSNotFound)
            {
                //替换agentid
                productDetailVC.gotoUrl = [productDetailVC.gotoUrl  stringByReplacingOccurrencesOfString:@"{agentid}" withString:[TRUserAgenCode getCustomerId]];
            }
            productDetailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:productDetailVC animated:YES];
        }
        else
        {
            [self judeLoginWithMessage:@"您还没登录，请先登录!"];
        }
    }
    else
    {
        if ([TRUserAgenCode isLogin])
        {
            productDetailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:productDetailVC animated:YES];
        }
        else
        {
            [self judeLoginWithMessage:@"您还没登录，请先登录!"];
        }
    }
}

#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", (long)index);
    JSONFromImages* images = self.imagesURLStrings1[index];
    ProductDetailViewController* productDetailVC = [[ProductDetailViewController alloc]initWithNibName:@"ProductDetailViewController" bundle:nil];
    productDetailVC.isFirst = YES;
    productDetailVC.isPush = YES;
    productDetailVC.gotoUrl = images.gotoUrl;
    productDetailVC.small_picture = images.small_picture;
    productDetailVC.product_features = images.product_features;
    productDetailVC.isSell = @"1";
    productDetailVC.target = images.target;
    if (![productDetailVC.gotoUrl isEqualToString:@""])
    {
        if ([productDetailVC.target isEqualToString:@"native"])
        {
            if ([TRUserAgenCode isLogin])
            {
                //替换agentid
                if ([productDetailVC.gotoUrl rangeOfString:@"{agentid}"].location != NSNotFound)
                {
                    productDetailVC.gotoUrl = [productDetailVC.gotoUrl  stringByReplacingOccurrencesOfString:@"{agentid}" withString:[TRUserAgenCode getCustomerId]];
                }
//                productDetailVC.isPush = NO;
//                [self presentViewController:productDetailVC animated:YES completion:nil];
                productDetailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:productDetailVC animated:YES];
            }
            else
            {
                [self judeLoginWithMessage:@"您还没登录，请先登录!"];
            }
        }
        else if ([productDetailVC.target isEqualToString:@"external"])
        {
            if ([TRUserAgenCode isLogin])
            {
                //替换agentid
                if ([productDetailVC.gotoUrl rangeOfString:@"{agentid}"].location != NSNotFound)
                {
                    productDetailVC.gotoUrl = [productDetailVC.gotoUrl  stringByReplacingOccurrencesOfString:@"{agentid}" withString:[TRUserAgenCode getCustomerId]];
                }
                productDetailVC.isPush = YES;
                productDetailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:productDetailVC animated:YES];
            }
            else
            {
                [self judeLoginWithMessage:@"您还没登录，请先登录!"];
            }
        }
    }
    else
    {
        //productDetailVC.gotoUrl 为空字符串，就直接不做跳转
    }
}

/*通知接口
 *
 *
 *
 *
 *
 *
 *
*/
//把活动、消息标题加入数组
- (NSArray*)getTitlesWithArr:(NSArray*)lists
{
    NSMutableArray* arr = [NSMutableArray array];
    for (LYMessageList* list in lists)
    {
        [arr addObject:list.title];
    }
    return [arr copy];
}

#pragma mark  //获取通知列表数据
- (void)postMessageList
{
//    //设置缓存的key
//    NSString* cacheStr = [NSString stringWithFormat:@"getMessagesList"];
    NSDictionary* json = @{@"page":@"1",
                           @"rows":@"10",
                           };
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@sign=%@",MessageURL,md5_Str];
    [self getMessageListWithURL:url withParam:json];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)getMessageListWithURL:(NSString*)url withParam:(NSDictionary*)param
{

    [XHNetworking POST:url parameters:param  success:^(NSData *responseObject) {
        //网络读取数据
        [self readMessageListWithData:responseObject];
    } failure:^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    }];
    
}

- (void)readMessageListWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"通知通知通知-----------");
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"])
            {
                if ([json[@"responseObject"] isKindOfClass:[NSDictionary class]])
                {
                    if ([json[@"responseObject"][@"rows"] isKindOfClass:[NSArray class]])
                    {
                        NSMutableArray* arr = [NSMutableArray array];
                        for (NSDictionary* dic in json[@"responseObject"][@"rows"])
                        {
                            LYMessageList* list = [LYMessageList messageListWithJSON:dic];
                            [arr addObject:list];
                        }
                        self.messages = [arr copy];
                    }
                    else
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                        });
                    }
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                    });
                }
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                });
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
            });
        }
        NSMutableArray* arr = [NSMutableArray array];
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            //只显示3条数据
            if (self.messages.count > 0)
            {
                if (self.messages.count > 3)
                {
                    [arr addObject:self.messages[0]];
                    [arr addObject:self.messages[1]];
                    [arr addObject:self.messages[2]];
                    self->_scrollTextView.textDataArr = [self getTitlesWithArr:[arr copy]];
                }
                else
                {
                    self->_scrollTextView.textDataArr = [self getTitlesWithArr:self.messages];
                }
            }
            //判断是否有未读消息
            //..................
            //..................
            //..................
            //..................
            //..................
        });
    });
}


//滚动视图的代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.tableView)
    {
        if (self.tableView.contentOffset.y <= self.headerView.frame.size.height - NavigationBarHeight - StatusBarHeight - TabBarHeight + 5)
        {
            self.sectionButtonsView.superDistance = - NavigationBarHeight - StatusBarHeight - TabBarHeight + 5;
        }
        else
        {
            self.sectionButtonsView.superDistance = self.headerView.frame.size.height - NavigationBarHeight - StatusBarHeight - TabBarHeight + 5;
        }
    }
}

#pragma mark  //获取首页分组列表
- (void)postGroupTypeList
{
    //设置缓存的key
    NSString* cacheStr = [NSString stringWithFormat:@"getGroupTypeList"];
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"getGroupTypeList",
                           @"requestObject":@{
                                   }
                           };
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self getGroupTypeListWithURL:url withParam:json withCacheStr:cacheStr];
}

//读取网络或本地的首页分组列表数据
- (void)readGroupTypeListWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"分组分组分组-----------");
    if ([json isKindOfClass:[NSDictionary class]] && json)
    {
        if ([json[@"resultCode"] isEqualToString:@"0"])
        {

            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                NSMutableArray* arr = [NSMutableArray array];
                for (NSDictionary* dict in json[@"responseObject"][@"groupTypeList"])
                {
                    JSONFromGroupTypeList* group = [JSONFromGroupTypeList groupTypeListWithJSON:dict];
                    [arr addObject:group];
                }
                self.sectionLists1 = [arr copy];
                
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self.tableView reloadData];
//                });
            });
            
            
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
            });
        }
    }
}

- (void)getGroupTypeListWithURL:(NSString*)url withParam:(NSDictionary*)param withCacheStr:(NSString*)cacheStr
{
    [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
        //网络读取数据
        [self readGroupTypeListWithData:responseObject];
    } failure:^(NSError *error) {
        NSLog(@"error.code = %@",error.userInfo);
        
        self.sectionLists1 = @[];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self endRefresh];
        });
    }];
}

#pragma mark  //获取产品列表

- (void)postPramaWithPageSize:(NSInteger)pageSize withPages:(NSInteger)pages withType:(NSString*)type
{
    //设置缓存的key
    NSString* cacheStr = [NSString stringWithFormat:@"getProductList_First_%ld_%ld_%ld",(long)pageSize,(long)pages,(long)self.buttonIndex];
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"getProductList",
                           @"requestObject":@{@"recommendCode":@"",
                                              @"groupType":type,
                                              @"brandId":@"",
                                              @"productDetailType":@"",
                                              @"isSell":@"1",
                                              @"pageParams":@{
                                                    @"currentPage":[NSString stringWithFormat:@"%ld",(long)pageSize],
                                                    @"pageSize":[NSString stringWithFormat:@"%ld",(long)pages],
                                                    @"queryAll":@"false"}
                                              }
                           };
    //字典类型转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
//    NSLog(@"MD5 = %@。md5.str = %@ ,JsonStr = %@",md5_Str,md5.str,str);
    [self getProductsWithURL:url withParam:json withCacheStr:cacheStr];
}


//读取网络或本地的产品列表数据
- (void)readProductsListWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"产品产品产品--------");
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"])
            {
                [CacheData removeCacheWith:@"ISSHOWTGF_666"];
                for (NSDictionary* dict in json[@"responseObject"][@"productList"])
                {
                    JSONFromProduct* product = [JSONFromProduct productWithJSON:dict];
                    [self.products1 addObject:product];
                }
                if ([json[@"responseObject"][@"pageParams"] isKindOfClass:[NSDictionary class]] && json[@"responseObject"][@"pageParams"])
                {
                    
                    
                    //总条数
                    NSInteger i1 = [json[@"responseObject"][@"pageParams"][@"pageTotal"] integerValue];
                    //当前页
                    NSInteger i2 = [json[@"responseObject"][@"pageParams"][@"currentPage"] integerValue];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [self.footer setHidden:NO];
                        if (i1 == i2)
                        {
                            [self.tableView.footer noticeNoMoreData];
                        };
                        if ([json[@"responseObject"][@"productList"] count] == 0)
                        {
                            [self.tableView.footer noticeNoMoreData];
                        }
                    });
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.footer setHidden:YES];
                    });
                }
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.footer setHidden:YES];
                });
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.footer setHidden:YES];
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endRefresh];
            if (self.products1.count == 0)
            {
                [self createWorkView];
            }
            else
            {
                [self removeWorkView];
            }
            [self.tableView reloadData];
        });
    });
}

- (void)getProductsWithURL:(NSString*)url withParam:(NSDictionary*)param withCacheStr:(NSString*)cacheStr
{
    [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
        
        //网络读取数据
        [self readProductsListWithData:responseObject];
        
    } failure:^(NSError *error) {
        NSLog(@"产品数据 = %@",self.products1);
        NSLog(@"error.code = %@",error.userInfo);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endRefresh];
            [self.footer setHidden:YES];
            
        });
    }];
}

//得到限时优惠，这行里面的按钮

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.products1.count > 0)
    {
        return self.products1.count;
    }
    else
    {
        return self.noNetworkArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.products1.count > 0)
    {
        FirstPageProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.TBButton.layer.cornerRadius = 17.0;
        cell.TBButton.layer.masksToBounds = YES;
        JSONFromProduct* product = self.products1[indexPath.row];
        cell.titleLabel.text = product.productName;
        cell.detailTitleLabel.text = product.product_features;
        cell.priceLabel.text = [NSString stringWithFormat:@"%@%@",product.product_price,product.product_unit];
        cell.typeLabelImageView.image = LoadImage(@"nav");
        if ([product.product_price isEqualToString:@"无"])
        {
            [cell.priceLabel setHidden:YES];
        }
        else
        {
            [cell.priceLabel setHidden:NO];
        }
        if (![product.groupName isEqualToString:@""])
        {
            [cell.typeLabelImageView setHidden:NO];
            [cell.typeLabel setHidden:NO];
            cell.typeLabel.text = product.groupName;
            cell.typeLabel.adjustsFontSizeToFitWidth = YES;
        }
        else
        {
            [cell.typeLabelImageView setHidden:YES];
            [cell.typeLabel setHidden:YES];
            cell.typeLabel.adjustsFontSizeToFitWidth = YES;
        }
        if (![cell.titleLabel.text isEqualToString:@""])
        {
            cell.titleLabel.backgroundColor = FFFFFFColor;
            cell.detailTitleLabel.backgroundColor = FFFFFFColor;
            cell.otherLabel.backgroundColor = FFFFFFColor;
            cell.TBButton.backgroundColor = FFFFFFColor;
            cell.priceLabel.backgroundColor = FFFFFFColor;
            
            cell.TBButton.layer.borderColor = KMainColor.CGColor;
            cell.TBButton.layer.borderWidth = 1.0;
            if ([product.isSell isEqualToString:@"1"])
            {
                [cell.TBButton setTitle:@"立即投保" forState:UIControlStateNormal];
            }
            else
            {
                [cell.TBButton setTitle:@"查看详情" forState:UIControlStateNormal];
            }
            [cell.TBButton addTarget:self action:@selector(pushTBVC:) forControlEvents:UIControlEventTouchUpInside];
            
            if (![cell.priceLabel.text isEqualToString:@""])
            {
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:cell.priceLabel.text];
                NSInteger i = product.product_unit.length;
                if (![product.product_unit isEqualToString:@""])
                {
                    [str addAttribute:NSForegroundColorAttributeName value:SHOWCOLOR(@"858585") range:NSMakeRange(cell.priceLabel.text.length - i,i)];
                    [str addAttribute:NSFontAttributeName value:SetFont(12) range:NSMakeRange(cell.priceLabel.text.length - i,i)];
                    [str addAttribute:NSForegroundColorAttributeName value:KMainColor range:NSMakeRange(0,cell.priceLabel.text.length - i)];
                    [str addAttribute:NSFontAttributeName value:SetFont(20) range:NSMakeRange(0,cell.priceLabel.text.length - i)];
                }
                else
                {
                    [str addAttribute:NSForegroundColorAttributeName value:KMainColor range:NSMakeRange(0,cell.priceLabel.text.length)];
                    [str addAttribute:NSFontAttributeName value:SetFont(20) range:NSMakeRange(0,cell.priceLabel.text.length)];
                }
                cell.priceLabel.attributedText = str;
            }
            
            cell.otherLabel.layer.borderWidth = 1.0;
            cell.otherLabel.layer.borderColor = SHOWCOLOR(@"34B0FE").CGColor;
        }
        else
        {
            cell.titleLabel.backgroundColor = F1F1F1Color;
            cell.detailTextLabel.backgroundColor = F1F1F1Color;
            cell.otherLabel.backgroundColor = F1F1F1Color;
            cell.TBButton.backgroundColor = F1F1F1Color;
            cell.priceLabel.backgroundColor = F1F1F1Color;
            [cell.typeLabelImageView setHidden:YES];
            [cell.typeLabel setHidden:YES];
            [cell.TBButton setTitle:@"" forState:UIControlStateNormal];
        }
        if ([product.promotion_expenses isEqualToString:@" 无"] || [product.promotion_expenses isEqualToString:@""])
        {
            cell.otherLabel.text = @"";
            [cell.otherLabel setHidden:YES];
        }
        else
        {
            if ([TRUserAgenCode isLogin])
            {
                NSNumber* number = [CacheData getCache:@"ISSHOWTGF"];
                if (number != nil)
                {
                    if ([number boolValue])
                    {
                        cell.otherLabel.text = [NSString stringWithFormat:@"推广费用%@",product.promotion_expenses];
                        [cell.otherLabel setHidden:NO];
                    }
                    else
                    {
                        cell.otherLabel.text = @"";
                        [cell.otherLabel setHidden:YES];
                    }
                }
                else
                {
                    cell.otherLabel.text = [NSString stringWithFormat:@"推广费用%@",product.promotion_expenses];
                    [cell.otherLabel setHidden:NO];
                }
            }
            else
            {
                cell.otherLabel.text = @"";
                [cell.otherLabel setHidden:YES];
            }
            //根据文字的多少自定义label的宽度
            NSDictionary *attrs = @{NSFontAttributeName : SetFont(10.0)};
            CGSize size=[cell.otherLabel.text sizeWithAttributes:attrs];
            [cell.otherLabel setFrame:CGRectMake(127+8, 71, size.width + 3, 14)];
        }
        cell.productPhotoView.contentMode = UIViewContentModeScaleAspectFill;
        [cell.productPhotoView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE_URL,product.small_picture]]
                                 placeholderImage:LoadImage(@"huakangtong_noNetwork.png")];
        if ([product.small_picture rangeOfString:HTTP].location != NSNotFound)
        {
            [cell.productPhotoView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",product.small_picture]]
                                     placeholderImage:LoadImage(@"huakangtong_noNetwork.png")];
        }
        return cell;
    }
    else
    {
        NoNetworkCell *cell = (NoNetworkCell*)[tableView dequeueReusableCellWithIdentifier:@"NoNetworkCell" forIndexPath:indexPath];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
}


#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.sectionLists1.count > 0)
    {
        return 66.0;
    }
    else
    {
        return 0.0;
    }
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.sectionLists1.count > 0)
    {
        self.sectionButtonsView = [[FirstPageSectionButtonsView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 66.0)];
        //    self.sectionButtonsView = [[FirstPageSectionButtonsView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 66.0)];
        self.sectionButtonsView.buttonIndex = self.buttonIndex;
        self.sectionButtonsView.buttons = self.sectionLists1;
        self.sectionButtonsView.distance = self.distance;
        [self.sectionButtonsView returnButtonTag:^(NSInteger buttonTag,NSString* group_type_id,CGFloat distance,CGFloat superDistance) {
            //当点击按钮，执行方法(全部产品、限时优惠、热卖劲爆)
            
            [self.products1 removeAllObjects];
            self.products1 = [NSMutableArray array];
            self.buttonIndex = buttonTag;
            self.group_type_id = group_type_id;
            self.slCount = 1;
            self.distance = distance;
            //self.myDistance = superDistance;
            NSLog(@"buttonTag = %ld  superDistance =%f",(long)buttonTag,superDistance);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self removeWorkView];
                if ([group_type_id integerValue] == 0)
                {
                    self.group_type_id = @"";
                }
                [self.tableView.footer resetNoMoreData];
                dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
                dispatch_after(delay, dispatch_get_main_queue(), ^{
                    //请求数据
                    [self postPramaWithPageSize:1 withPages:10 withType:self.group_type_id];
                });
            });
        }];
        [self.sectionButtonsView createButtons];
        return self.sectionButtonsView;
    }
    else
    {
        UIView* view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 0)];
        return view;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([cell isKindOfClass:[FirstPageProductCell class]] && self.products1.count > 0)
    {
        JSONFromProduct* product = self.products1[indexPath.row];
        ProductDetailViewController* productDetailVC = [[ProductDetailViewController alloc]initWithNibName:@"ProductDetailViewController" bundle:nil];
        //    productDetailVC.str = self.str;
        productDetailVC.isPush = YES;
        productDetailVC.isFirst = YES;
        productDetailVC.gotoUrl = product.gotoUrl;
        productDetailVC.productId = product.productCode;
        productDetailVC.isSell = product.isSell;
        productDetailVC.small_picture = product.small_picture;
        productDetailVC.product_features = product.product_features;
        //    productDetailVC.title = product.productName;
        if (![product.gotoUrl isEqualToString:@""])
        {
            if ([TRUserAgenCode isLogin])
            {
                if ([productDetailVC.gotoUrl rangeOfString:@"{agentid}"].location != NSNotFound)
                {
                    //替换agentid
                    productDetailVC.gotoUrl = [productDetailVC.gotoUrl  stringByReplacingOccurrencesOfString:@"{agentid}" withString:[TRUserAgenCode getCustomerId]];
                }
                //            UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:productDetailVC];
                productDetailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:productDetailVC animated:YES];
            }
            else
            {
                [self judeLoginWithMessage:@"您还没登录，请先登录!"];
            }
        }
        else
        {
            if ([TRUserAgenCode isLogin])
            {
                //                            productDetailVC.isPush = NO;
                //                            [self presentViewController:productDetailVC animated:YES completion:nil];
                productDetailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:productDetailVC animated:YES];
            }
            else
            {
                [self judeLoginWithMessage:@"您还没登录，请先登录!"];
            }
            //        productDetailVC.isPush = NO;
            //        [self presentViewController:productDetailVC animated:YES completion:nil];
        }
    }
}


@end
